
////////////////////////////////////////////////////////////////
$(function() {
  $(document).on('change','.entry-source-select',function(){
    var entry_source = $(this).val();
    if (entry_source) {
      var entry_type = $(this).attr('alt');
      var entry_id = Math.floor((Math.random() * 1000000000) + 1);
      $(this).closest(".nested-fields").find(".entry-fields").attr('id', 'entry-fields-'+entry_id);
      $.get("/records/entry.js", "&entry_type="+entry_type+"&entry_source="+entry_source+"&entry_id="+entry_id, null, "script");
      $(document).ajaxComplete(function(e) {
        $('.entry-data-section').show();
        $(e.currentTarget).unbind('ajaxComplete');
      });
    }
  });
  $(document).on('change','.entry-duration-select',function(){
    var enrty_point = $(this).closest(".nested-fields").find(".entry-data-point").text();
    var entry_level = $(this).closest(".entry-data-input").find(".entry-level-select").val();
    var entry_amount_abs = 0;
    var entry_amount = 0;
    if (entry_level) {
      var entry_duration = $(this).val();
      if (entry_duration) {
        entry_amount_abs = Math.round((enrty_point* entry_duration * entry_level) / 16);
        var entry_type = $(this).closest(".nested-fields").find(".entry-source-select").attr('alt');
        if(entry_type == "expense") {
          entry_amount = -entry_amount_abs;
        } else {
          entry_amount = entry_amount_abs;
        }
      }
    } 
    $(this).closest(".nested-fields").find(".entry-data-amount .label").text(entry_amount_abs);
    $(this).closest(".nested-fields").find(".entry-data-amount input").val(entry_amount);
  });
  $(document).on('change','.entry-level-select',function(){
    var enrty_point = $(this).closest(".nested-fields").find(".entry-data-point").text();
    var entry_duration = $(this).closest(".entry-data-input").find(".entry-duration-select").val();
    var entry_amount_abs = 0;
    var entry_amount = 0;
    if (entry_duration) {
      var entry_level = $(this).val();
      if (entry_level) {
        entry_amount_abs = Math.round((enrty_point * entry_duration * entry_level) / 16);
        var entry_type = $(this).closest(".nested-fields").find(".entry-source-select").attr('alt');
        if(entry_type == "expense") {
          entry_amount = -entry_amount_abs;
        } else {
          entry_amount = entry_amount_abs;
        }
      }
    }
    $(this).closest(".nested-fields").find(".entry-data-amount .label").text(entry_amount_abs);
    $(this).closest(".nested-fields").find(".entry-data-amount input").val(entry_amount);
  });
});

